package com.example.a1.myapplication.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.a1.myapplication.R;
import com.example.a1.myapplication.constants.SocketConstants;
import com.example.a1.myapplication.service.SocketService;
import com.example.a1.myapplication.socket.NetProxy;
import com.example.a1.myapplication.utils.BroadcastUtils;

public class SocketActivity extends AppCompatActivity {

    private EditText etContent;
    private TextView tvReceive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);
        etContent = findViewById(R.id.etContent);
        tvReceive = findViewById(R.id.tvReceive);
        startService(new Intent(getApplicationContext(), SocketService.class)
                .putExtra("socketUrl", "192.168.3.102")
                .putExtra("socketPort", 60000));
        findViewById(R.id.bSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NetProxy.send(etContent.getText().toString());
            }
        });
        BroadcastUtils.getInstance(this).registerReceiver(SocketConstants.SOCKET_ACTION, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tvReceive.setText(intent.getStringExtra(SocketConstants.SOCKET_MESSAGE));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BroadcastUtils.getInstance(this).unregisterReceiver(SocketConstants.SOCKET_ACTION);
    }
}
